package com.seari.custody.controller;

import cn.hutool.core.util.ReUtil;
import com.google.api.client.util.Lists;
import com.google.common.base.Preconditions;
import com.google.common.collect.Maps;
import com.seari.custody.bean.User;
import com.seari.custody.bean.UserDTO;
import com.seari.custody.bean.UserPersonalCenter;
import com.seari.custody.constant.MessageConstant;
import com.seari.custody.pojo.MessageBean;
import com.seari.custody.service.UserService;
import com.seari.custody.util.JwtTokenUtils;
import com.seari.custody.util.UUIDUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import static com.seari.custody.util.JwtTokenUtils.TOKEN_HEADER;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;


    /**
     * 注册新用户
     *
     * @param user
     * @return
     */
    @PostMapping("/register")
    public MessageBean registerUser(@RequestBody User user) throws Exception {

//        密码需要8-32位，且至少包含数字、字母和特殊符号中的两种。
        boolean isMatch = ReUtil.isMatch("^(?=.*[0-9].*)(?=.*[a-zA-Z].*).{8,32}$", user.getPassword());
        Preconditions.checkArgument(isMatch, "密码需要8-32位，且至少包含数字、字母和特殊符号中的两种");
        userService.save(user);
        return MessageBean.success("新增用户成功");
    }

    public static void main(String[] args) {
        boolean isMatch = ReUtil.isMatch("^(?=.*[0-9].*)(?=.*[a-zA-Z].*).{8,32}$", "A245678");
        System.out.println(isMatch);
    }

    @GetMapping("/qryName/{userNumber}")
    public MessageBean qryNameByUserNumber(@PathVariable String userNumber) {
        String name = userService.qryNameByUserNumber(userNumber);
        return MessageBean.success("查询用户名成功", name);
    }

    /**
     * 查询用户信息
     *
     * @param request
     * @renturn
     */
    @RequestMapping("/getUser")
    @ResponseBody
    public MessageBean getUserFoByToken(HttpServletRequest request) {
        MessageBean messageBean = new MessageBean();
        try {
            Map<String, Object> dataMap = new HashMap<String, Object>();
            List<User> lists = userService.getUserFoByToken(null);
            dataMap.put("date", lists);
            messageBean.setType(MessageConstant.SUCCESS_TYPE);
            messageBean.setCode(MessageConstant.SUCCESS);
            messageBean.setMessage("信息获取成功 ");
            messageBean.setData(dataMap);
        } catch (Exception e) {
            e.printStackTrace();
            messageBean.setType(MessageConstant.FAIL_TYPE);
            messageBean.setCode(MessageConstant.FAIL);
            messageBean.setMessage("信息获取失败");
        }
        return messageBean;
    }

    /**
     *
     */
    @GetMapping("/info")
    public MessageBean userInfo(@RequestHeader(value = TOKEN_HEADER, defaultValue = "") String token) {

        User info = userService.getInfo(token);
        HashMap<String, String> result = Maps.newHashMap();
        result.put("userName",info.getUsername());
        result.put("userNumber",info.getUserNumber());

        return MessageBean.success("获取用户信息成功", result);
    }


    /**
     * 新增用户信息
     *
     * @param ad
     * @return
     */
    @RequestMapping("/addUser")
    @ResponseBody
    public MessageBean addUser(User ad) {
        MessageBean messageBean = new MessageBean();
        String uuid = UUIDUtils.getUUID();
        /*String userName = ad.getUsername();
        String passWord = ad.getPassword();
        String role = ad.getRole();
        System.out.println("username" + userName+"k:"+passWord+"m:"+role);
        if (userName.isEmpty() || passWord.isEmpty() || role.isEmpty()){
            messageBean.setCode(MessageConstant.MESSAGE_TYPE_ERROR);
            messageBean.setMessage("信息不完整");
            return messageBean;
        }*/
        ad.setUuid(uuid);
        int resultNum = 0;
        resultNum = userService.addUser(ad);
        if (resultNum > 0) {
            messageBean.setType(MessageConstant.SUCCESS);
            messageBean.setCode(MessageConstant.SUCCESS_TYPE);
            messageBean.setMessage("新增用户成功");
        } else {
            messageBean.setType(MessageConstant.FAIL);
            messageBean.setCode(MessageConstant.FAIL_TYPE);
            messageBean.setMessage("新增用户失败");
        }
        return messageBean;
    }


    /**
     * //编辑用户信息
     *
     * @param et
     * @return
     */
    @RequestMapping("/updateUser")
    @ResponseBody
    public MessageBean updateUser(User et, HttpServletRequest request) {
        MessageBean messageBean = new MessageBean();
        Map<String, Object> dataMap = new HashMap<String, Object>();
        Map<String, Object> params = new HashMap<>();
        params.put("uuid", et.getUuid());
        params.put("username", et.getUsername());
        params.put("password", et.getPassword());
        params.put("role", et.getRole());
        int resultNum = 0;
        resultNum = userService.updateUser(params);
        if (resultNum > 0) {
            dataMap.put("data", "成功");
        }
        try {
            dataMap.put("ceshi", "成功内容");
            messageBean.setType(MessageConstant.SUCCESS);
            messageBean.setCode(MessageConstant.SUCCESS_TYPE);
            messageBean.setMessage("用户编辑成功");
        } catch (Exception e) {
            e.printStackTrace();
            messageBean.setType(MessageConstant.FAIL);
            messageBean.setCode(MessageConstant.FAIL_TYPE);
            messageBean.setMessage("用户编辑失败");
        }
        return messageBean;
    }


    /**
     * //删除用户信息
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "deleteUser")
    @ResponseBody
    public MessageBean deleteUser(String id) {
        MessageBean messageBean = new MessageBean();
        int resultNum = 0;
        resultNum = userService.deleteUser(id);
        if (resultNum > 0) {
            messageBean.setType(MessageConstant.SUCCESS);
            messageBean.setCode(MessageConstant.SUCCESS_TYPE);
            messageBean.setMessage("用户删除成功");
        } else {
            messageBean.setType(MessageConstant.FAIL);
            messageBean.setCode(MessageConstant.FAIL_TYPE);
            messageBean.setMessage("用户删除失败");
        }
        return messageBean;
    }

    /**
     * 下拉选择用户 过滤不包含自己
     */
    @GetMapping(value = "/selectUsers")
    public MessageBean users(@RequestHeader(value = TOKEN_HEADER, defaultValue = "") String token) {
        Preconditions.checkArgument(StringUtils.isNotEmpty(token), "token不能为空");
        String userNumber = JwtTokenUtils.getUserNumber(token.substring(JwtTokenUtils.TOKEN_PREFIX.length()));

        HashMap<String, List<UserDTO>> result = Maps.newHashMap();
        List<UserDTO> allUsers = userService.getAllUsers().stream().filter(f -> !Objects.equals(userNumber, f.getUserNumber())).collect(Collectors.toList());
        result.put("innerUsers", allUsers);
        List<UserDTO> externalUsers = Lists.newArrayList();
        //暂且写死
        externalUsers.add(new UserDTO("施工单位", ""));
        externalUsers.add(new UserDTO("建设单位", ""));
        externalUsers.add(new UserDTO("设计单位", ""));
        externalUsers.add(new UserDTO("其他单位", ""));
        result.put("externalUsers", externalUsers);

        return MessageBean.success("获取用户", result);

    }

    /**
     * 用户名模糊查询用户
     *
     * @param username
     * @return
     */
    @GetMapping(value = "/qry")
    public MessageBean qryUserByUserName(String username) {
        MessageBean messageBean = new MessageBean();

        List<UserDTO> users = userService.qryUserByName(username);
        messageBean.setData(users);
        messageBean.setCode(MessageConstant.SUCCESS);

        return messageBean;
    }

    /**
     * 个人中心
     * 根据UUID查询
     */
    @RequestMapping(value = "/queryPersonalCenter")
    public MessageBean personalCenter(@RequestBody Map<String, String> map) throws Exception {
        String username = map.get("username");
        MessageBean messageBean = new MessageBean();
        UserPersonalCenter user = userService.personalById(username);
        messageBean.setType(MessageConstant.SUCCESS_TYPE);
        messageBean.setCode(MessageConstant.SUCCESS);
        messageBean.setData(user);
        messageBean.setMessage("查询成功");
        return messageBean;
    }


    /**
     * 个人中心
     * 根据UUID修改
     */
    @RequestMapping(value = "/updatePersonalCenter")
    public MessageBean updatepersonalCenter(MultipartFile file, String usernumber, String name, String phone, String email, String password1, String password2) throws Exception {
        MessageBean messageBean = new MessageBean();

        try {
            //判断密码是否存在
            if (password1!= null && password1.length() != 0) {
                messageBean.setData("1");

            } else {
                messageBean.setData("0");
            }
            if (file == null) {
                userService.updatePersonalCenter(usernumber, name, phone, email, password1);
                messageBean.setCode(MessageConstant.SUCCESS);
                messageBean.setMessage("修改成功");
                return messageBean;
            }
            String contentType1 = file.getContentType();
            if (!contentType1.contains("image")) {
                messageBean.setCode(MessageConstant.FAIL);
                messageBean.setMessage("上传文件不为图片文件，请重新文件");
                return messageBean;
            }
            userService.updatePersonalCenter(file, usernumber, name, phone, email, password1);
            messageBean.setCode(MessageConstant.SUCCESS);
            messageBean.setMessage("修改成功");

        } catch (Exception e) {
            e.printStackTrace();
            messageBean.setType(MessageConstant.FAIL_TYPE);
            messageBean.setCode(MessageConstant.FAIL);
            messageBean.setMessage("个人中心修改失败");
        }
        return messageBean;
    }

    /**
     * 头像查看
     */
    @RequestMapping(value = "/headportraitServer")
    public MessageBean headportraitServer(@RequestHeader(value = TOKEN_HEADER, defaultValue = "") String token) throws Exception {
        String userNumber = JwtTokenUtils.getUserNumber(token.substring(JwtTokenUtils.TOKEN_PREFIX.length()));
        MessageBean messageBean = new MessageBean();
        String  user = userService.headportraitImg(userNumber);
        messageBean.setType(MessageConstant.SUCCESS_TYPE);
        messageBean.setCode(MessageConstant.SUCCESS);
        messageBean.setData(user);
        messageBean.setMessage("查询成功");
        return messageBean;
    }


}

